﻿using ProtoBuf;
using System;
using System.Collections.Generic;
using System.IO;
using VitServer;

namespace protoNet
{
    public class Serialize     //序列化类
    {
        //最终返回的可POST数组
        public byte[] SerializedBuffer
        {
            get;
            private set;
        }

        // 消息号
        public int msgId
        {
            get;
            private set;
        }

        public Serialize(GAME_PROTOCOL_MSG_ID id, object data)
        {
            msgId = Convert.ToInt32(id);
            SerializeBuffer(msgId, data);
        }

        private void SerializeBuffer(int id, object data)
        {
            //序列化对象
            MemoryStream ms = new MemoryStream();
            Serializer.Serialize<object>(ms, data);
            byte[] buffer = ms.ToArray();

            int serialLength = buffer.Length + 8;
            SerializedBuffer = new byte[serialLength];
            for (int i = 0, j = 0; i < serialLength; i++)
            {
                byte _buffer = 0;
                // 消息长度
                if (i < 4)
                {
                    _buffer = (byte)(buffer.Length >> 24 - 8 * i);
                    SerializedBuffer[i] = _buffer;
                }
                // 消息号
                else if (i < 8)
                {
                    _buffer = (byte)(id >> 24 - 8 * (i - 4));
                    SerializedBuffer[i] = _buffer;
                }
                // 包体
                else
                {
                    SerializedBuffer[i] = buffer[j++];
                }
            }
        }
    }
}
